package com.xu.ai.chatclient.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import jakarta.servlet.http.HttpServletResponse;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.metadata.ChatResponseMetadata;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.content.Media;
import org.springframework.http.MediaType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 通义千问多模态 controller
 *
 * @author xuguan
 * @since 2025/10/11
 */
@RestController
@RequestMapping("/api/multimodality")
public class MultimodalityController {

	public static final Logger log = LoggerFactory.getLogger(MultimodalityController.class);

	private final ChatClient chatClient;

	private final DashScopeChatModel dashScopeChatModel;

	public MultimodalityController(ChatClient.Builder chatClientBuilder, DashScopeChatModel dashScopeChatModel) {
		this.chatClient = chatClientBuilder
			.defaultOptions(DashScopeChatOptions.builder().withModel("qwen-plus").withMultiModel(true).build())
			.build();
		this.dashScopeChatModel = dashScopeChatModel.mutate()
			.defaultOptions(DashScopeChatOptions.builder().withModel("qwen3-vl-plus").withMultiModel(true).build())
			.build();
	}

	@GetMapping(value = "/image", produces = "text/html;charset=UTF-8")
	public Flux<String> image2Text() {
		final URI uri = URI.create("https://java2ai.com/img/user/ai/overview/1.0.0/spring-ai-alibaba-architecture.png");
		var userMessage = UserMessage.builder()
			.text("请用中文描述这张图片你看到了什么?") // content
			.media(new Media(MimeTypeUtils.IMAGE_PNG, uri)) // media
			.build();
		return dashScopeChatModel.stream(userMessage);
	}

	/**
	 * 通义千问文生图
	 */
	@GetMapping(value = "text2image")
	public void textToImage() {
		Map<String, Object> parameters = new HashMap<>();
		parameters.put("watermark", true);
		parameters.put("prompt_extend", true);
		parameters.put("negative_prompt", "");
		parameters.put("size", "1328*1328");
		final Prompt prompt = Prompt.builder()
			.messages(UserMessage.builder().text("空山新雨后, 天气晚来秋. 根据这句诗绘制出一张自然景色图片.").metadata(parameters).build())
			.chatOptions(DashScopeChatOptions.builder().withModel("qwen-image-plus").withMultiModel(true).build())
			.build();
		final ChatResponse chatResponse = dashScopeChatModel.call(prompt);
		final ChatResponseMetadata metadata = chatResponse.getMetadata();

		final String url = chatResponse.getResult().getOutput().getText();
		log.info("url: {}", url);

		if (StringUtils.hasText(url)) {
			try (InputStream is = URI.create(url).toURL().openStream()) {
				final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
					.currentRequestAttributes();
				final HttpServletResponse response = requestAttributes.getResponse();
				// 设置图片的Content-Type
				response.setContentType(MediaType.IMAGE_JPEG_VALUE); // 根据实际图片类型调整
				// 获取response输出流并写入图片数据
				OutputStream os = response.getOutputStream();
				os.write(is.readAllBytes());
				os.flush();
			}
			catch (IOException e) {
				throw new RuntimeException("Failed to read or write image: " + url, e);
			}
		}
	}

	@GetMapping(value = "edit-image")
	public void editImage() {

	}

}
